package com.hubing.cloud.app.web.controller;

import com.alibaba.fastjson2.JSONObject;
import com.hubing.cloud.app.web.constant.EsConstant;
import com.hubing.cloud.app.web.es.ElasticSearchRestManager;
import com.hubing.cloud.app.web.es.PaginationBean;
import com.hubing.cloud.app.web.model.ResponseBean;
import com.hubing.cloud.app.web.model.dto.SearchDto;
import com.hubing.cloud.app.web.service.MenuService;
import com.hubing.cloud.app.web.service.NavigationService;
import com.hubing.cloud.app.web.service.SearchHotService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 主页（检索、热搜推荐、文档导航）
 */
@Slf4j
@RestController
@RequestMapping("home")
public class HomeController {

    @Autowired
    private NavigationService navigationService;

    @Autowired
    private SearchHotService searchHotService;

    @Autowired
    private MenuService menuService;

    /**
     * 热门搜索列表、文档导航列表
     *
     * @return
     */
    @PostMapping("/navigation")
    public ResponseBean navigation() {
        JSONObject result = new JSONObject();
        result.put("hotSearch",searchHotService.queryHot());
        result.put("docNavigation",navigationService.queryNavigation());
        result.put("menu", menuService.queryMenu());
        return ResponseBean.success(result);
    }

    /**
     * 全文检索
     *
     * @param dto
     * @return
     */
    @PostMapping("/search")
    public ResponseBean search(@RequestBody SearchDto dto) {
        String[] indices = new String[]{EsConstant.DOC_INDEX};
        String[] types = new String[]{EsConstant.TYPE};

        PaginationBean<Map<String, Object>> page =
                ElasticSearchRestManager.getPagination(indices, types, createDocQuery(dto), dto.getPageNo() - 1, dto.getPageSize(), null);

        List<String> meunId = ElasticSearchRestManager.distinct(indices[0], "rootMenuId", createDistinctMenuQuery(dto))
                .stream().map(String::valueOf).collect(Collectors.toList());

        JSONObject result = new JSONObject();
        result.put("list", page.getResult()); // 检索结果
        result.put("count", page.getTotalRows()); // 检索总数
        result.put("menu",menuService.queryByIds(meunId)); // 检索涉及到菜单
        return ResponseBean.success(result);
    }

    private BoolQueryBuilder createDocQuery(SearchDto dto) {
        BoolQueryBuilder query = QueryBuilders.boolQuery();
        if (StringUtils.isNotEmpty(dto.getRootMenuId())) {
            query.filter(QueryBuilders.termQuery("rootMenuId",dto.getRootMenuId()));
        }
        BoolQueryBuilder should = QueryBuilders.boolQuery()
                .should(QueryBuilders.matchQuery("docTextContent", dto.getContent()))
                .should(QueryBuilders.matchQuery("docTitle", dto.getContent()));
        query.filter(should);
        return query;
    }

    private BoolQueryBuilder createDistinctMenuQuery(SearchDto dto) {
        BoolQueryBuilder query = QueryBuilders.boolQuery();
        BoolQueryBuilder should = QueryBuilders.boolQuery()
                .should(QueryBuilders.matchQuery("docTextContent", dto.getContent()))
                .should(QueryBuilders.matchQuery("docTitle", dto.getContent()));
        query.filter(should);
        return query;
    }

}
